<template>
	<view class="page">
		<!-- <up-navbar :title="`${type==0 ? '生词本' : type==1 ?'熟词本' :'模糊词本' }(${count}词)`" @rightClick="{}" :autoBack="true"
			bgColor="#f1f1f1" placeholder></up-navbar> -->

		<view class="fontSize-28">
			<view class="width-full box-sizing paddingTop-20 paddingLeft-30 paddingRight-30 paddingBottom-20">
				<view class="" style="width: 100%; height: 38px;">
					<up-input clearable @focus="focus" @clear="clear" @confirm="search" v-model="searchVal"
						:adjustPosition="false" confirmType="search" placeholder="请输入搜索关键字">
						<template #suffix>
							<up-icon @click="search" name="search" size="18"></up-icon>
						</template>

					</up-input>
				</view>
			</view>
			<view class="relative" style="width: 100%;height: 60rpx;">
				<view class="export_btn" @click="download">
					导出
				</view>
			</view>
			<view class="width-full flex column paddingBottom-200">
				<view class="" v-if="newWordList.length==0">
					<image src="../../static/noWord-img.png" mode="" class="width-160 height-160"
						style="display: block; margin: 0 auto; margin-top: 268rpx;"></image>
					<view class="fontSize-28 color-999 marginTop-40 text-center">
						该生词本暂无相关词哦
					</view>
				</view>
				<view class="flex column width-full " v-for="(it,index) in newWordList" :key="index ">
					<up-collapse accordion>
						<up-collapse-item>
							<template #title>
								<view
									class="width-full box-sizing paddingLeft-40 paddingRight-40 paddingBottom-20 paddingTop-20 borderRadius-6 items-center flex space-between"
									style="background-color: #f1f1f1;color: #565656;">
									<view class="" v-if='type == 2'>
										{{it.px}}
									</view>
									<view class="" v-if='type == 0&&it.total_page!=0'>
										第{{it.total_page}}页
									</view>
									<view class="" v-else>
										待记生词
									</view>
									<view class="">
										{{it.count}}词
									</view>
								</view>
							</template>

							<view style="border-bottom: 1rpx solid #e0e0e0;"
								class=" width-full items-center flex space-between box-sizing paddingLeft-40 paddingRight-40 paddingBottom-20 paddingTop-20"
								v-for="(t,i) in it.wordlist" :key="i" @click.stop='clickword(t.wordHead,it,t,i)'>
								<view class="flex items-center u-line-1" >
									<view class="" v-if="isShow&&it.total_page==0">
										<image src="../../static/weixuanzhong.png" mode="" class="sec_img"
											v-if="!t.select"></image>
										<image src="../../static/xuanzhong.png" mode="" class="sec_img" v-else></image>
									</view>
									<view class="flex column fontSize-26 width-half ">
										<view class="word-section">
											<view class="wordHead-text">
												{{t.wordHead}}
											</view>
											<view class="phone-text">
												{{t.phone}}
											</view>
										</view>

										<view class="  " style="color: #7b7b7b;">
											<span v-for="(p,j) in returnVal(t.tran)" class="u-line-1" style="width: 300rpx;">{{p}}</span>
										</view>
									</view>
								</view>
								<view class="">
									<view class="flex" @click="type == 2?getPopupList(t):''">
										<view class="total-text" v-if="type == 2">
											({{t.is_know}})
										</view>
										<view class="total-text">
											{{t.xh}}
										</view>
									</view>
									<view v-if="type == 2" style="font-size: 24rpx;">
										{{t.create_time}}
									</view>
								</view>

							</view>
						</up-collapse-item>

					</up-collapse>

				</view>
			</view>

		</view>
		<up-popup :safeAreaInsetBottom="false" mode="center" closeable round="5" :show="phoneShow" @close="close"
			@open="phoneShow = true">
			<view class="popupBox fontSize-28">
				<view class="width-full weight-700 text-center">
					{{emitData.page}}
				</view>
				<view class="width-full weight-700" style="color: #666;">
					{{emitData.subscript}}块
				</view>

				<view class="flex column marginTop-30">
					<view class="flex items-center space-between height-120" v-for="(it,i) in emitData.wordList"
						:key="i">
						<view class="fontSize-30 weight-700" style="min-width: 200rpx;">
							{{parseInt(i)+1}}.{{it.wordHead}}
						</view>

						<view class="width-full">
							<view class="wordsDefaultText fontSize-24 ">
								<view class="marginBottom-5" v-for="(t,id) in returnVal(it.tran)" :key="id">
									{{t}}
								</view>
							</view>

						</view>

					</view>
				</view>
			</view>
		</up-popup>

		<!-- <view class="width-full box-sizing btns flex column items-center flex-center">
			<view  class="marginTop-30 flex flex-center" style = "width: 80vw;">
				<up-button  @click="btnClick" size = "normal" type="primary"  text="确定"></up-button>
			</view>
		</view> -->
		<up-action-sheet :actions="showList" :show="show" cancelText='取消' @select='selectShow' :round='25'
			@close='closeShow'></up-action-sheet>

		<view class="pos flex items-center space-between" v-if="isShow">
			<view class="flex items-center" @click="allClick()">
				<image src="../../static/weixuanzhong.png" mode="" class="sec_img" v-if="!allShow"></image>
				<image src="../../static/xuanzhong.png" mode="" class="sec_img" v-else></image>
				<view class="pos_title">
					全选
				</view>
			</view>
			<view class="flex items-center">
				<view class="cancel" @click="cancel()">
					取消
				</view>
				<view class="pos_btn" @click="yiru">
					移入熟词本
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		inject
	} from 'vue'
	import {
		onLoad,
		onUnload,
		onShow
	} from '@dcloudio/uni-app'
	const secondstatApi = inject('Secondstat')
	const show = ref(false)
	const newwordsbookApi = inject('newwordsbook')
	const getAreaWordsViewApi = inject('getAreaWordsView')
	const newwordsbookcountApi = inject('newwordsbookcount')
	const exportWordsApi = inject('exportWords')
	const noWordShow = ref(false)
	const showList = ref([{
			name: '移入熟词本',
			value: 1,
		},
		{
			name: '批量操作',
			value: 2,
		}
	])
	// data
	// 假设你有一个后端接口可以返回 Excel 文件的下载链接  
	const downloadExcel = async (url) => {
		try {
			// 使用 uni.downloadFile 下载文件  
			const res = await uni.downloadFile({
				url: url, // 后端提供的下载链接  
				success: (downloadRes) => {
					if (downloadRes.statusCode === 200) {
						// 文件下载成功，使用 uni.saveFile 保存文件  
						uni.saveFile({
							tempFilePath: downloadRes.tempFilePath, // 临时文件路径  
							success: (saveRes) => {
								// 文件保存成功，saveRes.savedFilePath 为保存后的文件路径  
								console.log('文件保存成功：', saveRes.savedFilePath);
								// 你可以在这里提示用户文件已保存，或者打开文件  
								uni.openDocument({
									filePath: saveRes.savedFilePath,
									fileType: 'xlsx',
									showMenu: true,
									success: () => {
										uni.showToast({
											title: '打开文档成功',
											icon: 'success',
											mask: true,
										});
									},
									fail: (error) => {
										console.log('error', error);
									},
								});

							},
							fail: (err) => {
								console.error('文件保存失败：', err);
							},
						});
					} else {
						console.error('文件下载失败，状态码：', downloadRes.statusCode);
					}
				},
				fail: (err) => {
					console.error('文件下载失败：', err);
				},
			});
		} catch (error) {
			console.error('下载过程中发生错误：', error);
		}
	};

	// 调用下载函数，传入后端提供的下载链接  

	const info = ref({})
	const practic_id = ref('')
	const popupList = ref([])
	const newWordList = ref([])
	const phoneShow = ref(false);
	const emitData = ref({})
	const count = ref('')
	const type = ref(0) //0生词 2模糊词 1熟词
	const searchVal = ref('')

	const download = () => {

		exportWordsApi({


		}).then(res => {
			console.log(res, 'tttttttttt')
			if (res.status == 201) {
				uni.showToast({
					title: res.msg,
					icon: "none",
					duration: 3000
				})
			} else {
				downloadExcel(res);
			}
		})
	}
	const clear = () => {
		searchVal.value = '';
		newWordList.value = [];
		newwordsList();
	}
	const search = () => {
		// if(!searchVal.value) return
		newwordsList();
	}
	const focus = () => {

	}
	const newwordsList = () => {
		newwordsbookApi({
			type: type.value,
			keyword: searchVal.value

		}).then(res => {
			console.log(res, 'tttttttttt')
			newWordList.value = res
			console.log('newWordList', newWordList.value)


			if (res.length == 0) {
				noWordShow.value = true

			}
		})
	}
	const countList = () => {
		newwordsbookcountApi({

		}).then(res => {
			console.log(res, '111111111111')
			if (type.value == 0) {
				count.value = res.unknow_count
			} else if (type.value == 1) {
				count.value = res.know_count
			} else {
				count.value = res.blur_count
			}
		})
	}
	onLoad((t) => {
		type.value = t.type
		newwordsList()
		countList()

	})
	onUnload(() => {
		clearTimeOut();

	})
	const close = () => {
		phoneShow.value = false
	}
	const getPopupList = (t) => {
		getAreaWordsViewApi({
			page: t.total_page,
			big_sort: t.total_big_sort,
			small_sort: t.total_small_sort,
		}).then(res => {
			emitData.value['subscript'] = t.total_big_sort + '-' + t.total_small_sort
			emitData.value['page'] = t.is_know + '第' + t.total_page + '页'
			emitData.value['wordList'] = res.wordList
			phoneShow.value = true

		})
	}

	const returnVal = (val) => {
		let valList = val.split('<br>');
		let text = ''
		for (let s of valList) {
			text = `
				${text}
				${s}
			`
		}
		return valList
	}




	const btnClick = () => {
		uni.navigateTo({
			// url:''
		})
	}

	const innerAudioContext = uni.createInnerAudioContext();
	//音频播放
	innerAudioContext.autoplay = false;

	innerAudioContext.onCanplay(() => {
		// console.log('可以播放l ');
		// setTimeout(() => { 
		// console.log('开始播放');
		// innerAudioContext.play()
		// }, 1000)
	});
	innerAudioContext.onPlay((e) => {

		// console.log('音频播放事件', e);
	})
	innerAudioContext.onEnded((e) => {

		// _this.voiceLoading = false
		// console.log('音频自然播放结束事件', e);
	})
	const timer = ref({});

	const play = (i, time, word) => {
		if (true) {
			timer.value['t' + i] = setTimeout(() => {
				innerAudioContext.stop();
				innerAudioContext.src = `https://dict.youdao.com/dictvoice?audio=${word}&type=1`;
				innerAudioContext.play();
			}, time);
		}
	}
	const clearTimeOut = () => {
		if (timer.value) {
			let arr = Object.keys(timer.value)
			for (let s of arr) {
				console.log(timer.value[s])
				clearTimeout(timer.value[s]);
			}
		}

	}
	const wordId = ref('')
	const clickword = (t, it, t2, i) => {
		console.log(t, it, t2, i, 364)
		if (!isShow.value) {
			if (it.total_page == 0) {
				show.value = true
				wordId.value = t2.wordId
				console.log(wordId.value)
			}
		} else {
			t2.select = !t2.select
		}
		clearTimeOut()
		for (var i = 0; i < 3; i++) {
			play(i, i * 2000, t)
		}

	}
	const isShow = ref(false)
	const selectShow = (e) => {
		console.log(e);
		if (e.value == 1) {
			movenewword()
		} else {
			isShow.value = true
		}
	}
	const closeShow = () => {
		show.value = false
	}
	const yiru = () => {
		let arr = []
		newWordList.value.forEach((item, index) => {
			item.wordlist.forEach((i, v) => {
				if (item.total_page == 0) {
					if (i.select) {
						arr.push(i.wordId)
					}
				}
			})
		})
		wordId.value = arr.join(',')
		console.log(wordId.value)
		movenewword()
	}

	const allClick = () => {
		allShow.value = !allShow.value
		if (allShow.value) {
			newWordList.value.forEach((item, index) => {
				item.wordlist.forEach((i, v) => {
					if (item.total_page == 0) {
						i.select = true
					}

				})
			})
		} else {
			newWordList.value.forEach((item, index) => {
				item.wordlist.forEach((i, v) => {
					if (item.total_page == 0) {
						i.select = false
					}
				})
			})
		}
	}
	const allShow = ref(false)
	const cancel = () => {
		// show.value = false
		isShow.value = false
		wordId.value = ''
		allShow.value = false
	}

	const movenewword = () => {
		if(wordId.value==''){
			uni.showToast({
				title:"请选择要移除数据",
				icon:'none'
			})
			return
		}
		movenewwordApi({
			wordId: wordId.value,
		}).then(res => {
			newwordsList()
			countList()
			cancel()
		})
	}
	const movenewwordApi = inject('movenewword')
</script>

<style lang="scss" scoped>
	.btns {
		padding-bottom: calc(50rpx);
	}

	.imageBox {
		width: 100%;
		height: 120rpx;

		image {
			border-radius: 8rpx;
			height: 100%;
			width: 100%;
		}
	}

	.popupBox {
		width: 80vw;
		padding: 50rpx 30rpx 30rpx;
		// background-color: #fff;
		// border-radius: 5px;
		box-sizing: border-box;

		.btns {
			// padding-bottom: calc(50rpx);
		}
	}

	.bjf1 {
		background-color: #f1f1f1;
	}

	.width-half {
		width: 55%;
	}

	.word-section {
		display: flex;

		.wordHead-text {
			color: #333;
			font-size: 28rpx;
		}

		.phone-text {
			color: #666;
			margin-left: 10rpx;
		}
	}

	.total-text {
		font-size: 26rpx;
		color: #51D580;
	}

	::v-deep .u-cell__body.data-v-3fd6feca {
		background-color: #f1f1f1;
		font-size: 26rpx;
		padding: 0 20rpx;
	}

	::v-deep .u-collapse-item__content__text.data-v-82f3baf9 {
		padding: 0;
	}

	.export_btn {
		position: absolute;
		right: 30rpx;
		background-color: #40D577;
		width: 100rpx;
		height: 40rpx;
		text-align: center;
		line-height: 40rpx;
		color: #fff;
		font-size: 24rpx;
		border-radius: 5rpx;
	}

	.sec_img {
		width: 38rpx;
		height: 38rpx;
		margin-right: 10rpx;
	}

	.pos {
		width: 690rpx;
		height: 130rpx;
		background: #F5F5F5;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		padding: 20rpx 30rpx;
		position: fixed;
		bottom: 0rpx;

		.pos_title {
			font-weight: 500;
			font-size: 30rpx;
			color: #333333;
			margin-left: 12rpx;
		}

		.cancel {
			font-weight: 500;
			font-size: 30rpx;
			color: #999999;
			margin-right: 50rpx;
		}

		.pos_btn {
			width: 202rpx;
			height: 86rpx;
			background: #51D580;
			border-radius: 92rpx 92rpx 92rpx 92rpx;
			text-align: center;
			line-height: 86rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #FFFFFF;
		}
	}
</style>